﻿namespace Home.Logging
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public static class Log
    {
        private static readonly string LineSeparator = new string('-', 20);

        public static void Information(string format, params object[] args)
        {
            Trace.TraceInformation(format, args);
        }

        public static void Warning(string format, params object[] args)
        {
            Trace.TraceWarning(format, args);
        }

        public static void Error(string format, params object[] args)
        {
            Error(null, format, args);
        }

        public static void Error(Exception exception, string format, params object[] args)
        {
            var message = new StringBuilder();
            FormatException(exception, message);
            message.AppendFormat(format, args);
            message.AppendLine();
            message.AppendFormat("{1}{0}", Environment.NewLine, LineSeparator);
            Trace.TraceError(message.ToString());
        }

        private static void FormatException(Exception exception, StringBuilder message)
        {
            while (exception != null)
            {
                message.AppendFormat("Message: {1}{0}", Environment.NewLine, exception.Message);
                message.AppendFormat("StackTrace:{0}{1}{0}", Environment.NewLine, exception.StackTrace);

                var aggregateException = exception as AggregateException;
                if (aggregateException != null)
                {
                    foreach (var innerException in aggregateException.InnerExceptions)
                    {
                        FormatException(innerException, message);
                    }
                }

                exception = exception.InnerException;
            }
        }
    }
}
